package com.core.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.core.utils.MyUtils;

public class DBDriver {

	/**
	 * 
	 * @Title getConnection
	 * @Description TODO (创建链接数据库驱动实例对象)
	 * @return Connection 返回链接数据库链接的实例对象
	 * @throws 捕获sql异常
	 * 
	 */
	public Connection getConnection() {
		Connection connection = null;
		try {
//			String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEnding=utf-8&useSSL=false";
//			String user = "root";
//			String password = "root";
			Properties pro=new Properties();
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("db.properties");
			pro.load(is);
			String url = pro.getProperty("url");
			String user = pro.getProperty("user");
			String password = pro.getProperty("password");
			
			connection = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			// TODO 打印sql错误站信息
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 * 
	 * @Title doQuery
	 * @Description TODO (根据sql语句，得到查询结果集)
	 * @param sql 执行的sql语句
	 * @return ResultSet 返回查询结果集
	 * @throws 捕获sql异常
	 */
	public ResultSet doQuery(String sql) {
		ResultSet query = null;
		try {
			//创建查询数据库对象
			Statement statement = getConnection().createStatement();
			//根据sql语句执行，执行之后得到查询结果集
			query = statement.executeQuery(sql);
		} catch (SQLException e) {
			// TODO 打印sql错误站信息
			e.printStackTrace();
		}

		return query;
	}
	/**
	 * 
	 * @Title doQuery
	 * @Description TODO (根据sql语句，得到查询结果集)
	 * @param sql 执行的sql语句
	 * @return ResultSet 返回查询结果集
	 * @throws 捕获sql异常
	 */
	public List<Map<String,Object>> doQueryList(String sql) {
		ResultSet query = this.doQuery(sql);
		List<Map<String,Object>> resultSetConverList = MyUtils.resultSetConverList(query);
		return resultSetConverList;
	}
	/**
	 * 
	 * @param <T>
	 * @Title doQuery
	 * @Description TODO (根据sql语句，得到查询结果集)
	 * @param sql 执行的sql语句
	 * @return ResultSet 返回查询结果集
	 * @throws 捕获sql异常
	 */
	public <T> List<T> doQueryBean(String sql,Class<T> tclass) {
		ResultSet query = this.doQuery(sql);
		return MyUtils.resultSetConverBean(query,tclass);
	}
	
	
	
	
	
	/**
	 * 
	 * @Title close
	 * @Description TODO (关闭链接驱动对象)
	 * @return void 无返回类型
	 * @throws 捕获sql异常
	 */
	public void close() {
		try {
			if(getConnection()!=null&&getConnection().isClosed()) {
				getConnection().close();
			}
		} catch (SQLException e) {
			// TODO 打印sql错误站信息
			e.printStackTrace();
		}
	}
}
